package parser

import (
	"fmt"
	"github.com/Exleryz/gorequest"
	"github.com/PuerkitoBio/goquery"
	"regexp"
	"save-kindle/source/ddd/definition"
	"save-kindle/source/ddd/dp"
	"strings"
)

var _ definition.Parser = (*Parser1)(nil)

func NewParser1() Parser1 {
	return Parser1{
		ParserName: "1115文学解析器",
	}
}

// Parser1 115文学解析器
type Parser1 struct {
	ParserName definition.ParserName
	// 书源规则
}

func (p Parser1) ParserChapterList(bookCatalog dp.BookCatalog) []dp.BookChapter {
	_, catalogHtml, _ := gorequest.New().
		Get(bookCatalog.CatalogUrl).
		End()

	doc, _ := goquery.NewDocumentFromReader(strings.NewReader(catalogHtml))
	chapterList := make([]dp.BookChapter, 0)
	// class
	doc.Find(".mulu_uld").Each(func(i int, selection *goquery.Selection) {
		selection.Find("li").Each(func(i int, selection *goquery.Selection) {
			// 章节解析
			h, e := selection.Html()
			// 0 <a href="http://wap.115wx.cc/book/jiuriyulong/1.html" class="click sprites"><h3><i>&gt;</i>1、最后的时代</h3></a> <nil> >1、最后的时代
			fmt.Println(i, h, e, selection.Text())
			// fixme 这里可以优化
			chapterUrl, ok := selection.Find("a").Attr("href")
			if !ok {
			}

			title := p.ParserChapterTitle(selection.Find("a[href]").Text())

			chapter := dp.NewBookChapter(i, title, chapterUrl)
			chapterList = append(chapterList, chapter)
		})
	})
	return chapterList
}

func (p Parser1) ParserChapterTitle(title string) string {
	// 数字0次及以上
	// 、 0次或1次
	subMatch := regexp.MustCompile(">\\d*、*(.*)").
		FindAllStringSubmatch(title, -1)
	if len(subMatch) > 0 {
		title = subMatch[0][1]
	}
	return title
}

func (p Parser1) ParserChapterUrl() string {
	return ""
}

func (p Parser1) GetPageUrl(chapter dp.BookChapter, pageNo int) string {
	// http://wap.115wx.cc/book/jiuriyulong/1.html
	pageUrlTemp := "http://wap.115wx.cc/book/jiuriyulong/%d%s.html"
	pageSuffix := ""
	if pageNo > 1 {
		pageSuffix = fmt.Sprintf("_%d", pageNo)
	}

	return fmt.Sprintf(pageUrlTemp, chapter.Index+1, pageSuffix)
}

func (p Parser1) ParserPage(chapter dp.BookChapter, pageNo int) string {
	pageUrl := p.GetPageUrl(chapter, pageNo)
	_, respStr, _ := gorequest.New().
		Get(pageUrl).
		End()

	doc, _ := goquery.NewDocumentFromReader(strings.NewReader(respStr))
	// id
	pageHtml, _ := doc.Find("#rd-txt").Html()
	return pageHtml
}

func (p Parser1) HasNextPage(pageHtml string) bool {
	return strings.Contains(pageHtml, "next.png")
}

func (p Parser1) ParserContent(pageHtml string) []string {
	lines := make([]string, 0)

	doc, _ := goquery.NewDocumentFromReader(strings.NewReader(pageHtml))
	pList := doc.Find("p")
	pList.Each(func(i int, selection *goquery.Selection) {
		html, _ := selection.Html()
		html = strings.Trim(html, " ")
		fmt.Println(i, html)

		// 这里是可以有处理逻辑的
		// 去掉首尾
		if i == 0 || i == pList.Size()-1 {
			return
		}

		lines = append(lines, html)
	})

	return lines
}
